const express = require('express');
const auditService = require('../services/auditService');
const llmService = require('../services/llmService');
const { authMiddleware } = require('../middleware/auth');

const router = express.Router();

// 所有审核接口都需要认证
router.use(authMiddleware);

/**
 * GET /api/audit/pending
 * 获取待审核记录列表
 */
router.get('/pending', async (req, res) => {
  try {
    const { page = 1, pageSize = 20 } = req.query;

    const result = await auditService.getPendingAuditRecords(
      parseInt(page),
      parseInt(pageSize)
    );

    res.json(result);
  } catch (error) {
    console.error('获取待审核记录失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * GET /api/audit/detail/:id
 * 获取记录详情（原始+处理后）
 */
router.get('/detail/:id', async (req, res) => {
  try {
    const { id } = req.params;

    const result = await auditService.getRecordWithProcessedData(parseInt(id));

    res.json(result);
  } catch (error) {
    console.error('获取记录详情失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * POST /api/audit/submit
 * 提交审核（自动使用当前登录用户信息）
 */
router.post('/submit', async (req, res) => {
  try {
    const { rawPersonnelId, auditStatus, comment, updatedData } = req.body;

    if (!rawPersonnelId || !auditStatus) {
      return res.status(400).json({
        success: false,
        message: '缺少必填参数'
      });
    }

    // 自动使用当前登录用户的信息作为审核人
    const auditorName = req.user.realName;
    const auditorId = req.user.employeeId;

    const result = await auditService.auditRecord(
      parseInt(rawPersonnelId),
      auditStatus,
      auditorName,
      auditorId,
      comment,
      updatedData
    );

    res.json(result);
  } catch (error) {
    console.error('审核失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * POST /api/audit/batch
 * 批量审核（自动使用当前登录用户信息）
 */
router.post('/batch', async (req, res) => {
  try {
    const { auditList } = req.body;

    if (!auditList || !Array.isArray(auditList)) {
      return res.status(400).json({
        success: false,
        message: '参数错误'
      });
    }

    // 自动使用当前登录用户的信息作为审核人
    const auditorName = req.user.realName;
    const auditorId = req.user.employeeId;

    const result = await auditService.batchAudit(auditList, auditorName, auditorId);

    res.json(result);
  } catch (error) {
    console.error('批量审核失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * GET /api/audit/statistics
 * 获取审核统计
 */
router.get('/statistics', async (req, res) => {
  try {
    const result = await auditService.getAuditStatistics();

    res.json(result);
  } catch (error) {
    console.error('获取审核统计失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * GET /api/audit/records
 * 获取已审核记录列表
 */
router.get('/records', async (req, res) => {
  try {
    const { status = 'all', page = 1, pageSize = 20 } = req.query;

    const result = await auditService.getAuditedRecords(
      status,
      parseInt(page),
      parseInt(pageSize)
    );

    res.json(result);
  } catch (error) {
    console.error('获取已审核记录失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * POST /api/audit/ai-audit/:id
 * AI审核：对比提取的数据与原文
 */
router.post('/ai-audit/:id', async (req, res) => {
  try {
    const { id } = req.params;

    console.log(`收到AI审核请求，记录ID: ${id}`);

    // 获取记录详情
    const record = await auditService.getRecordWithProcessedData(parseInt(id));
    
    if (!record.success) {
      return res.status(404).json({
        success: false,
        message: record.message || '记录不存在'
      });
    }

    const { processedRecord } = record;

    if (!processedRecord) {
      return res.status(404).json({
        success: false,
        message: '处理后的数据不存在'
      });
    }

    // 准备提取的数据
    const extractedData = {
      chinese_name: processedRecord.chinese_name,
      english_name: processedRecord.english_name,
      gender: processedRecord.gender,
      birth_date: processedRecord.birth_date,
      age: processedRecord.age,
      email: processedRecord.email,
      phone: processedRecord.phone,
      graduate_school: processedRecord.graduate_school,
      education_level: processedRecord.education_level,
      military_branch: processedRecord.military_branch,
      military_rank: processedRecord.military_rank,
      organization: processedRecord.organization,
      current_position: processedRecord.current_position,
      position_start_date: processedRecord.position_start_date,
      work_status: processedRecord.work_status
    };

    // 调用AI审核
    const auditResult = await llmService.aiAudit(
      extractedData,
      processedRecord.chinese_biography
    );

    res.json(auditResult);
  } catch (error) {
    console.error('AI审核失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

module.exports = router;

